package com.papa91.arc;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.res.AssetManager;
import android.media.AudioManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.RemoteException;
import android.os.Vibrator;
import android.util.Log;
import android.view.KeyEvent;
import android.widget.Toast;

import com.join.mgps.joystick.KeyMapController;
import com.join.mgps.joystick.KeyMapController.OnKeyMapListener;
import com.join.mgps.joystick.map.KeyMap.EmuMap;
import com.join.mgps.joystick.map.KeyMapEvent;
import com.papa91.activity.EmuBaseActivity;
import com.papa91.arcapp.AppConfig;
import com.papa91.common.MyJson;
import com.tencent.bugly.crashreport.CrashReport;

import org.json.JSONArray;
import org.json.JSONException;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.Socket;

public class EmuActivity extends EmuBaseActivity implements OnKeyMapListener, Runnable
{
	public static String BUGLY_ID = "900009495";
	public static String APP_KEY = "CvjvU1occ4UCTVEe";
	public static String AD_APP_KEY = "1105599035";
	static Handler m_handler = new Handler()
	{
		@Override
		public void handleMessage(Message msg)
		{
			startAPPActivity();
			super.handleMessage(msg);
		}

	};

	public static String cpuFreq = getCurCpuFreq(1);
	public static String cpuNum = "" + Runtime.getRuntime().availableProcessors();

	public static final boolean SINGLE_MODE = false;
	private static final boolean IS_USER_V1 = false;
	private static Vibrator vibrtor;
	int firstKey = 0;

	private static String recordfn = "";

	private static native int setJson(String json);

	private static native int initLaunchConfig(String[] key, String[] value);

	private static native int initEmu();

	private static native int exitEmu();

	private static native int setPadVisible(int isVisible, int canUseJoystick);

	private static native int showDailog(int code);

	public static native void setJoyStickKey(int[] key);

	private static EmuActivity emuActivity;

	public static String coreName = "FBA_V2";
	private Socket socket;
	private Thread thread = null;
	private int roomSilent;

	public static void saveConfig(String key, String value)
	{
		// SharedPreferences sp =
		// PreferenceManager.getDefaultSharedPreferences(getContext());
		SharedPreferences sp = getContext().getSharedPreferences("core", Activity.MODE_PRIVATE);
		Editor edit = sp.edit();
		edit.putString(key, String.valueOf(value));
		edit.commit();
	}

	public static String getRecordInfo(String path)
	{
		String suffix = "";
		if (coreName.equals("FBA_V2"))
			suffix = "_v2";
		return EmuBaseActivity.getRecordInfo(path + suffix);
	}

	public static boolean setImageToMEDIA(String file)
	{
		Intent scanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);

		scanIntent.setData(Uri.fromFile(new File(file)));

		emuActivity.sendBroadcast(scanIntent);

		return true;
	}

	public static void exitActivty(int code)
	{

		if (startMode == AppConfig.START_MODE_NETWORK)
		{
			Intent intent = new Intent("papa_broadcast_continue_match_fight");
			intent.putExtra("game_end_state", code);
			emuActivity.sendBroadcast(intent);
		}

		try
		{
			//	uploadEfficiencyData();

			int dt = (int) (System.currentTimeMillis() - startTIme);

			if (aidlService != null)
			{
				aidlService.gameOut(GameID, dt, UserID);
			}
		} catch (RemoteException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/*
	 * public static void printLogCat(int a, int b, int c, int d) {
	 * 
	 * // emuLogCat(String gameId, String uid, String packageName, String //
	 * version)
	 * 
	 * Log.e("zcylog15", "zcylog15 printLogCat a=" + a + "b=" + b + "c=" + c +
	 * "d=" + d); try {
	 * 
	 * 
	 * String errorInfo = ""; switch (a) { case 2: errorInfo = "SIGINT"; break;
	 * case 4: errorInfo = "SIGILL"; break; case 8: errorInfo = "SIGFPE"; break;
	 * case 11: errorInfo = "SIGSEGV"; break; case 15: errorInfo = "SIGTERM";
	 * break; case 21: errorInfo = "SIGBREAK"; break; case 22: errorInfo =
	 * "SIGABRT"; break; }
	 * 
	 * String pkName = getContext().getPackageName(); String versionName = "";
	 * try { versionName = getContext().getPackageManager().getPackageInfo(
	 * pkName, 0).versionName; } catch (NameNotFoundException e) { // TODO
	 * Auto-generated catch block e.printStackTrace(); }
	 * aidlService.emuLogCat(GameID, UserID, pkName, versionName, errorInfo); }
	 * catch (RemoteException e) { // TODO Auto-generated catch block
	 * e.printStackTrace(); } }
	 */

	public static void delayStatistics(String json)
	{
		try
		{
			AppConfig.logD(json);
			aidlService.netBattleMatchEfficiency(GameID, json, UserID);
		} catch (RemoteException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public static String getCurCpuFreq(int index)
	{

		// /*
		String result = "";
		ProcessBuilder cmd;
		try
		{
			String[] args =
			{ "/system/bin/cat", "/sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_max_freq"// "/sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_max_freq"
			};
			cmd = new ProcessBuilder(args);
			Process process = cmd.start();
			InputStream in = process.getInputStream();
			byte[] re = new byte[24];
			while (in.read(re) != -1)
			{
				result = result + new String(re);
			}
			in.close();
		} catch (IOException ex)
		{
			ex.printStackTrace();
			result = "N/A";
		}
		return result.trim();
		// */
		/*
		 * String result = "N/A"; try { FileReader fr = new FileReader(
		 * "/sys/devices/system/cpu/cpu0/cpufreq/scaling_cur_freq");
		 * BufferedReader br = new BufferedReader(fr); String text =
		 * br.readLine(); result = text.trim(); } catch (FileNotFoundException
		 * e) { e.printStackTrace(); } catch (IOException e) {
		 * e.printStackTrace(); } return result;
		 */
		/*
		 * String str1 = "/proc/cpuinfo"; String str2=""; String[]
		 * cpuInfo={"",""}; String[] arrayOfString; try { FileReader fr = new
		 * FileReader(str1); BufferedReader localBufferedReader = new
		 * BufferedReader(fr, 8192); str2 = localBufferedReader.readLine();
		 * arrayOfString = str2.split("\\s+"); for (int i = 2; i <
		 * arrayOfString.length; i++) { cpuInfo[0] = cpuInfo[0] +
		 * arrayOfString[i] + " "; } str2 = localBufferedReader.readLine();
		 * arrayOfString = str2.split("\\s+"); cpuInfo[1] += arrayOfString[2];
		 * localBufferedReader.close(); } catch (IOException e) { } return
		 * cpuInfo[index];
		 */
	}

	public void updateConfig()
	{
		SharedPreferences sp = this.getSharedPreferences("core", Activity.MODE_PRIVATE);
		enableAudio = sp.getString(AppConfig.PREF_ENABLE_AUDIO, "1");

		screenMOde = sp.getString(AppConfig.PREF_SCREEN_MODE, "1");

		vibriorMode = sp.getString("vibriorMode", "1");

		version = sp.getString("version", "1.4.0");
	}

	public static void playerVibrtor()
	{
		vibrtor.vibrate(50);
	}

	public static void startForumsActivity()
	{
		Message mes = new Message();
		handler.sendMessage(mes);

	}

	// 自动加载rom
	public void createRom()
	{
		AssetManager asset = this.getAssets();

		try
		{
			String sdDir = Environment.getExternalStorageDirectory().getAbsolutePath();
			File file = new File(sdDir, "mslug5.zip");

			InputStream istream = asset.open("mslug5.zip", AssetManager.ACCESS_BUFFER);

			OutputStream ostream = new FileOutputStream(file);
			byte[] buf = new byte[1024];
			int len;
			while ((len = istream.read(buf)) > 0)
			{
				ostream.write(buf, 0, len);
			}
			ostream.flush();
			ostream.close();
			istream.close();
			// asset.close();

			String json = "{\"romPath\":\"" + sdDir + "/mslug5" + "\",\"startMode\":" + 0 + ",\"userID\":\"" + "2000"
					+ "\",\"gameID\":\"509474702\",\"version\":\"2\",\"roomID\":\"10000\",\"serverIP\":\"121.201.0.114\",\"serverPort\":\"5369\",\"porder\":" + 0 + "}"; // test
			if (json != null)
				setJson(json);

		} catch (IOException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	public void loadRom()
	{
		String[] keyArray =
		{ "screenMode", "appPath", "libPath", "enableAudio", "vibriorMode", "gameMode"
		};
		String[] valueArray =
		{ screenMOde, AppConfig.APP_PATH, AppConfig.getLibpath(this), enableAudio, vibriorMode, "FBA"
		};
		initLaunchConfig(keyArray, valueArray);

		createRom();

		initEmu();
	}

	private static void openUrl()
	{
		String url = "http://h5.papa91.com/sp_jiesuo.html"; // web address

		Intent intent = new Intent(Intent.ACTION_VIEW);

		intent.setData(Uri.parse(url));

		emuActivity.startActivity(intent);

	}

	public static void complainPlayer(String username, int uuid, int self_uuid)
	{
		complain(uuid, self_uuid);
	}

	String getCore(String path)
	{
		if (startMode == 15)
		{
			if (recordfn.indexOf("_v2") == -1)
				return "FBA";
			else
				return "FBA_V2";
		}

		if (IS_USER_V1)
			return "FBA";

		if ((0 == startMode && roomSilent == 0))
		{
			romName = path.substring(path.lastIndexOf("/") + 1, path.length());
			if (AppConfig.isPgmGame(romName))
			{
				String record = AppConfig.APP_PATH + romName + "/" + romName;
				for (int cnt = 0; cnt <= 100; cnt++)
				{
					File file = new File(record + "." + cnt);
					if (file.exists())
					{
						return "FBA";
					}
				}

			}
			return "FBA_V2";
		}
		else if (14 == startMode)
		{
			return "FBA_V2";
		}
		else
		{
			return "FBA";
		}

		/*
			int begin = path.lastIndexOf("/");
			int end = path.length();
			String romName = path.substring(begin + 1, end);
			if (path.endsWith("hookj") || path.endsWith("nbbatman") || path.endsWith("uccops") || path.endsWith("inhunt") || path.endsWith("ssoldier"))
			{
				return "FBA_V2";
			}
			String checkFile = path.substring(0, path.lastIndexOf("/") + 1) + "fba_v2.cfg";
			if (new File(checkFile).exists())
			{
				return "FBA_V2";
			}
			if (0 == startMode && path.endsWith("mslug5"))
			{
				return "FBA_V2";
			}
			if(IS_USER_V1)
				return "FBA";
			if (0 == startMode && AppConfig.isPgmGame(romName)){
				return "FBA_V2";
			}
			String record = AppConfig.APP_PATH + romName + "/" + romName;
			AppConfig.logE("getCore " + record);
			Date gbalibStateModifiedTime = null;
			for (int cnt = 0; cnt <= 100; cnt++)
			{
				File file = new File(record + "." + cnt);
				if (file.exists())
				{
					Date lastModified = new Date(file.lastModified());
					if (gbalibStateModifiedTime == null || lastModified.after(gbalibStateModifiedTime))
					{
						gbalibStateModifiedTime = lastModified;
					}
				}
			}
			Date vbaStateModifiedTime = null;
			for (int cnt = 0; cnt <= 100; cnt++)
			{
				File file = new File(record + "_v2." + cnt);
				if (file.exists())
				{
					Date lastModified = new Date(file.lastModified());
					if (vbaStateModifiedTime == null || lastModified.after(vbaStateModifiedTime))
					{
						vbaStateModifiedTime = lastModified;
					}
				}
			}
			if (gbalibStateModifiedTime != null && vbaStateModifiedTime != null)
			{
				if (gbalibStateModifiedTime.after(vbaStateModifiedTime))
				{
					//startMode = 0;
					return "FBA";
				}
				else
				{
					return "FBA_V2";
				}
			}
			else if (gbalibStateModifiedTime == null)
			{
				return "FBA_V2";
			}
			else
			{
				startMode = 0;
				return "FBA";
			}
		*/
	}

	@Override
	public void onCreate(Bundle savedInstanceState)
	{

//		TelephonyManager tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
//		DEVICE_ID = tm.getDeviceId();
		Log.e("onCreate", "onCreate 111");
		setVolumeControlStream(AudioManager.STREAM_MUSIC);
		emuActivity = this;
		CrashReport.initCrashReport(getApplicationContext(), BUGLY_ID, false);
		vibrtor = (Vibrator) getSystemService(this.VIBRATOR_SERVICE);

		Log.e("onCreate", "onCreate 222");
		Intent intent = getIntent();

		if (intent != null)
		{
			String path = intent.getStringExtra(AppConfig.KEY_ROM_PATH);
			if (path != null && path != "")
			{
				romPath = path;
				AppConfig.logD("json ........................... rompath : " + romPath);
			}

		}
		AppConfig.initialise(EmuActivity.this);

		// AppConfig.updateConfig(getContext());
		updateConfig();
		Log.e("onCreate", "onCreate 222");
		onLoadNativeLibraries();
		Log.e("onCreate", "onCreate 33");
		String jstring = intent.getStringExtra(AppConfig.KEY_START_JSON);
		MyJson myJson = null;
		if (jstring != null)
		{

			try
			{
				myJson = new MyJson(jstring);

			} catch (JSONException e)
			{
				e.printStackTrace();
			}

			if (null != myJson)
			{
				appPackName = myJson.getString(AppConfig.PA_PACKAGE_NAME, appPackName);
				startMode = myJson.getInt(AppConfig.KEY_START_MODE, 0);
				romPath = myJson.getString(AppConfig.KEY_ROM_PATH, "");
				UserID = myJson.getString(AppConfig.KEY_START_USERID, "");
				GameID = myJson.getString(AppConfig.KEY_START_GAMEID, "");
				fid = myJson.getInt(AppConfig.KEY_START_FID, 0);
				RoomID = myJson.getString(AppConfig.KEY_START_ROOMID, "");
				Version = myJson.getString(AppConfig.KEY_START_VERSION, "");
				server_ip = myJson.getString(AppConfig.KEY_SERVER_IP, "");
				server_port = myJson.getString(AppConfig.KEY_SERVER_PORT, "");
				AppConfig.curPlayer = myJson.getInt(AppConfig.KEY_START_PORDER, 0);
				token = myJson.getString("token", "0");
				spLock = myJson.getInt(AppConfig.KEY_SP_LOCK, 0);
				m_SVIP = myJson.getInt(AppConfig.KEY_SVIP_LEVEL, 0);
				m_VIP = myJson.getInt(AppConfig.KEY_VIP_LEVEL, 0);
				roomSilent = myJson.getInt("", 0);
				allowPeripheralJoin = myJson.getBoolean("allowPeripheralJoin", true);
				JSONArray jsonArray = myJson.getJSONArray(AppConfig.AD_JSON_KEY, null);
				if (null != jsonArray)
					initBanner(jsonArray, AD_APP_KEY);
				try
				{
					myJson.put("device", getPhoneInfo());
					myJson.put("device_id", DEVICE_ID);

				} catch (JSONException e)
				{
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				if (startMode == 15)
				{
					recordfn = myJson.getString(AppConfig.KEY_NET_STATE, "");
				}
			}
			CrashReport.setUserId(GameID);

			AppConfig.logE("...................KEY_START_FID : " + String.valueOf(fid));

			// startAPPActivity();

			// int startMode = intent.getIntExtra(AppConfig.KEY_START_MODE, 0);
			Log.i("EMUACTIVITY", jstring);
			coreName = getCore(romPath);
			AppConfig.logE("getCore " + coreName);

			String[] keyArray =
			{ "screenMode", "appPath", "libPath", "enableAudio", "vibriorMode", "version", "cpuNum", "cpuFreq", "sp_lock", "gameMode"
			};
			String[] valueArray =
			{ screenMOde, AppConfig.APP_PATH, AppConfig.getLibpath(this), enableAudio, vibriorMode, version, cpuNum, cpuFreq, spLock + "", coreName
			};
			initLaunchConfig(keyArray, valueArray);
			try
			{
				myJson.put(AppConfig.KEY_START_MODE, startMode);
				myJson.put("device_id", DEVICE_ID);
			} catch (JSONException e)
			{
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			setJson(dealSDPath(myJson.toString(), AppConfig.APP_PATH));
			initEmu();
		}
		else
		{
			loadRom();
		}
		Log.e("onCreate", "onCreate 44");
		super.onCreate(savedInstanceState);
		if (allowPeripheralJoin)
		{
			KeyMapController.getInstance().register(this, EmuMap.FBA);
			KeyMapController.getInstance().setOnKeyMapListener(this);
		}

	}

	@Override
	public boolean dispatchKeyEvent(KeyEvent event)
	{

		//	testThread();
		int keyCode = event.getKeyCode();
		if (keyCode == KeyEvent.KEYCODE_VOLUME_UP || keyCode == KeyEvent.KEYCODE_VOLUME_DOWN)
			return super.dispatchKeyEvent(event);
		if (firstKey == keyCode && event.getAction() == KeyEvent.ACTION_UP)
		{
			if (keyCode == KeyEvent.KEYCODE_BACK)
			{
				showDailog(0);
			}

		}
		else
		{
			firstKey = keyCode;
			return super.dispatchKeyEvent(event) | KeyMapController.getInstance().onKeyDispatcher(event);
		}

		return super.dispatchKeyEvent(event) | !KeyMapController.getInstance().onKeyDispatcher(event);

	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event)
	{

		// showDailog(0);
		if (keyCode == KeyEvent.KEYCODE_BACK && !AppConfig.IsXperiaPlay())
		{
			// showDailog(0);
		}
		return super.onKeyDown(keyCode, event);
	}

	@Override
	public void onResume()
	{
		super.onResume();
	}

	@Override
	public void onPause()
	{
		super.onPause();
	}

	@Override
	protected void onDestroy()
	{
		Log.d("NETPLAY", "onDestroy");
		KeyMapController.getInstance().unregister();
		super.onDestroy();
		exitEmu(); // qyh fix exit bug
		System.exit(0);
	}

	@Override
	public void onVirtualKeyboard(boolean hide)
	{
		// TODO Auto-generated method stub
		int i = 0;
		if (allowPeripheralJoin)
			i = 1;
		if (hide)
			setPadVisible(0, i);
		else
			setPadVisible(1, i);
	}

	static void setBlueTooth()
	{

		KeyMapController.getInstance().pullConnectionState();
	}

	@Override
	public void onKeyMap(int[] arg0, KeyMapEvent arg1, KeyEvent arg2)
	{
		if (!allowPeripheralJoin)
			return;

		setJoyStickKey(arg0);
		// setJoyStickKey(EmuActivity.keyVaule);

	}

	protected void testThread()
	{
		if (null != thread)
			return;
		thread = new Thread(this);

		thread.start();

	}

	public byte[] readBytes(byte[] buffer, InputStream stream) throws IOException
	{
		int bytes = 0;
		while (bytes < buffer.length)
		{
			int n = stream.read(buffer, bytes, buffer.length - bytes);
			if (n < 0)
				throw new IOException();
			bytes += n;
		}
		return buffer;
	}

	protected void startKeyDemo()
	{

		int port = 12345;

		try
		{
			socket = new Socket("192.168.71.163", port);

			/*		Log.d("EmuActivity11",""+ "=="+socket.getInputStream().read()+"");
					byte[] buffer = new byte[4] ;
					Log.d("EmuActivity11","run");
					buffer = readBytes(buffer,socket.getInputStream());*/
			byte[] buffer = new byte[4];
			BufferedReader is = new BufferedReader(new InputStreamReader(socket.getInputStream()));
			//InputStream in=socket.getInputStream();
			while (true)
			{
				{
					buffer = readBytes(buffer, socket.getInputStream());
					int res = ((buffer[3] << 8) & 0xff000000) | ((buffer[2] << 8) & 0xff0000) | ((buffer[1] << 8) & 0xff00) | (buffer[0] & 0xff);
					Log.d("EmuActivityend", "res == " + res);
					if (res >= 0)
					{
						int[] keys = new int[4];
						keys[0] = res;
						setJoyStickKey(keys);
					}
				}
			}

		} catch (IOException e)
		{
			// TODO Auto-generated catch block
			Toast.makeText(this, "连接失败", Toast.LENGTH_SHORT).show();
			Log.d("EmuActivity11", "连接失败");
			//	startKeyDemo();
			e.printStackTrace();
		}

	}

	@Override
	public void run()
	{
		// TODO Auto-generated method stub
		startKeyDemo();
	}

	@Override
	public void onGenericMotionEvent(int arg0, float arg1, float arg2)
	{
		// TODO Auto-generated method stub

	}
}
